package ex2b.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Point2D;

import javax.swing.JPanel;

import ex2b.controller.Controller;

public class ProductsPanel extends JPanel {

	private static final long serialVersionUID = 1L;
	private Controller controller = null;
	private Dimension d = null;
	private Point2D.Double center;
	private Ellipse2D.Double product;
	private double raio;
	
	public ProductsPanel() {
		controller = Controller.getInstance();
		controller.setProductsPanel( this );
		d = new Dimension();
		center = new Point2D.Double();
		product = new Ellipse2D.Double();
		
		setBackground( Color.WHITE );
		setForeground( Color.BLACK );
		
	}
	
	@Override
	public void paintComponent( Graphics _g ) {
		Object[] products = controller.getProducts();
		Graphics2D g = (Graphics2D) _g;
		
		if( products == null ) return;
		
		double width, height, oldWidth, offset;
		double doisPi = Math.PI * 2.0;
		double angulo = doisPi / products.length;
		int i = 0;
        
		d = getSize( d );
		oldWidth = width = d.getWidth();
		height = d.getHeight();
		
		g.setColor( Color.WHITE );
		g.fillRect( 0, 0, (int) width, (int) height );
		
		if( width > height ) {
			width = height;
		} else if( width < height ) {
			height = width;
		}
		
		raio = ( width / products.length );
		
		offset = ( ( oldWidth - width ) / 2.0 );
		
		center.x = width / 2.0;
		center.y = height / 2.0;
		
		center.y *= 0.975;
		
		product.height = product.width = raio;
		
		g.setColor( Color.BLACK );
		g.setFont( new Font("Comic Sans", Font.BOLD, (int) ( product.width * 5 ) ) );
		g.drawString( Integer.toString( controller.getTotalProduzido() ), (float) ( offset + center.x ), (float)( center.y + height / 8 ) );
		
		g.setFont( new Font("Comic Sans", Font.BOLD, (int) ( product.width ) ) );
		
		for( i = 0; i < products.length; ++i ) {
			product.x = offset + center.x + ( center.x * Math.cos( ( - angulo ) * i ) );
			product.y = center.y + ( center.y * Math.sin( ( - angulo ) * i ) );
			
			if( products[ i ] != null ) {
				g.setColor( Color.BLACK );
				g.drawString( products[ i ].toString(), (int)product.getCenterX(), (int)product.getCenterY() );
			} else {
				g.setColor( Color.RED );
				g.fill( product );
			}
		}
	}
}
